package net.aiion.weave.impl.web.servlet.http;

import java.util.Objects;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import net.aiion.weave.spi.startup.Startup;

@WebListener
public class WeaveServletSessionListener implements HttpSessionListener
{
    public static final String SESSION_CONTEXT_ID_PARAMETER = "org.weaveframework.web.impl.servlet.http.sessionContext";

    public WeaveServletSessionListener() {
    }

    @Override
    public void sessionCreated(final HttpSessionEvent aHttpSessionEvent) {
        final HttpSession httpSession = aHttpSessionEvent.getSession();
        final String assumedSessionContextId = String.valueOf(httpSession.getAttribute(SESSION_CONTEXT_ID_PARAMETER));
        final String realSessionContextId = Startup.getInstance().usingGlobalContext()
            .usingSessionContext(assumedSessionContextId).getSessionContextId();
        if (!Objects.equals(assumedSessionContextId, realSessionContextId)) {
            httpSession.setAttribute(SESSION_CONTEXT_ID_PARAMETER, realSessionContextId);
        }
    }

    @Override
    public void sessionDestroyed(final HttpSessionEvent aHttpSessionEvent) {
        final HttpSession httpSession = aHttpSessionEvent.getSession();
        final String sessionContextId = String.valueOf(httpSession.getAttribute(SESSION_CONTEXT_ID_PARAMETER));
        Startup.getInstance().usingGlobalContext().usingSessionContext(sessionContextId).executeShutdown();
        httpSession.removeAttribute(SESSION_CONTEXT_ID_PARAMETER);
    }
}
